package ws

import (
	"encoding/json"
	"ims/app/dao"
	"ims/tools"

	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/gorilla/websocket"
)

func KefuLogin(token string) (map[string]interface{}, error) {

	userinfo, valid := tools.JwtParseToken(token)
	if valid != nil {
		return nil, gerror.New("jwt授权失败1!")
	}
	g.Log().Debug("kefuLogin:{}", userinfo)
	// map[id:11 type:kefu]
	if userinfo == nil {
		return nil, gerror.New("jwt授权失败2!")
	}
	jti := gconv.Map(userinfo["jti"])
	admininfo := dao.GetChatServiceByIdOrUserId(gconv.String(jti["id"]), gconv.String(jti["id"]))
	//验证 token是否过期
	if admininfo.Id == 0 {
		return nil, gerror.New("您登录的客服用户不存在")
	}
	g.Log().Debug(admininfo)
	user := dao.GetChatUserInfoById(admininfo.UserId)
	if user.Id > 0 {
		dao.UpdateChatUser(map[string]string{"online": "1"}, user.Id)
	}

	return map[string]interface{}{
		"uid":        user.Uid,
		"type":       "kefu",
		"toUserId":   0, //暂时不知道 和谁聊天
		"avatar":     user.Avatar,
		"is_tourist": user.IsTourist,
		"nickname":   user.Nickname,
		"user_id":    user.Id,
		"online":     1,
		"appid":      admininfo.Appid,
	}, nil
}

func KefuToChat(message *Message) {
	var typeMsg TypeMessage
	json.Unmarshal(message.content, &typeMsg)

	td := gjson.New(typeMsg.Data)
	to_user_id := td.GetInt("id")
	g.Log().Debug("===================================kefu to chat is:", to_user_id)
	//测试时候用
	// to_user_id = 861
	//获取当前聊天用户
	wsconn := CurrentWsconn(message)
	if wsconn != nil {
		wsconn.ToUserID = to_user_id
		//设置它要聊天的对象
		ChatRoom[wsconn.UID] = wsconn
	}

	data := make(map[string]interface{})
	data["user_id"] = wsconn.UserId
	data["recored"] = make(map[string]string)
	data["num"] = 0
	msg := TypeMessage{
		Type:   "mssage_num",
		Data:   data,
		Status: 200,
	}
	str, _ := json.Marshal(msg)
	Mux.Lock()
	message.conn.WriteMessage(websocket.TextMessage, str)
	Mux.Unlock()
}
